#include "select.h"
#include "ui_select.h"
#include <QSqlDatabase>
#include <QSqlError>
#include <QMessageBox>
#include <QDebug>
#include <QCoreApplication>

Select::Select(QWidget *parent)
    : QWidget(parent), ui(new Ui::Select)
{
    ui->setupUi(this);
    
    // 确保数据库连接存在
    QSqlDatabase db = QSqlDatabase::database();
    if (!db.isValid() || !db.isOpen()) {
        qDebug() << "数据库连接无效，尝试重新连接";
        db = QSqlDatabase::addDatabase("QSQLITE");
        QString dbPath = QCoreApplication::applicationDirPath() + "/sever.db";
        db.setDatabaseName(dbPath);
        qDebug() << "Select类数据库路径:" << dbPath;
        if (!db.open()) {
            QMessageBox::warning(this, "数据库错误", "无法连接到数据库: " + db.lastError().text());
            return;
        }
    }
    
    model = new QSqlTableModel(this, db);
}

Select::~Select()
{
    delete ui;
}

void Select::on_selectBt_clicked()
{
    if (!model) {
        QMessageBox::warning(this, "错误", "数据模型未初始化");
        return;
    }
    
    // 检查数据库连接
    QSqlDatabase db = model->database();
    if (!db.isValid() || !db.isOpen()) {
        QMessageBox::warning(this, "数据库错误", "数据库连接无效");
        return;
    }
    
    if (ui->empRb->isChecked())
    {
        model->setTable("employee");
    }
    else if (ui->attRb->isChecked())
    {
        model->setTable("attendance");
    }
    else {
        QMessageBox::information(this, "提示", "请选择要查询的表");
        return;
    }
    
    if (!model->select()) {
        QMessageBox::warning(this, "查询错误", "查询失败: " + model->lastError().text());
        return;
    }
    
    ui->tableView->setModel(model);
    ui->tableView->resizeColumnsToContents();
}
